package cn.achao.csr.chat.dao;

import cn.achao.csr.api.model.entity.ChatUser;
import cn.achao.csr.api.model.enums.ChatActiveStatusEnum;
import cn.achao.csr.base.resp.CursorPageBaseResp;
import cn.achao.csr.chat.mapper.ChatUserMapper;
import cn.achao.csr.mybatis.req.MPBaseCursorPageReq;
import cn.achao.csr.tool.utils.CursorUtils;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChatUserDao extends ServiceImpl<ChatUserMapper, ChatUser> {

    private final CursorUtils cursorUtils;
    private final ChatUserMapper userMapper;

    public Map<Long, ChatUser> getUserListByIds(List<Long> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return new HashMap<>();
        }

        return lambdaQuery()
                .in(ChatUser::getId, userIds)
                // 添加列表查询方法，并通过Stream转换为Map
                .list()
                .stream()
                .collect(Collectors.toMap(
                        ChatUser::getId,
                        Function.identity(),
                        (existing, replacement) -> existing  // 处理重复键（根据需求选择处理策略）
                ));
    }

    public Number getOnlineCount(List<Long> memberUidList) {
        return lambdaQuery()
                .eq(ChatUser::getOnlineStatus, ChatActiveStatusEnum.ONLINE.getStatus())
                .in(CollectionUtil.isNotEmpty(memberUidList), ChatUser::getId, memberUidList)
                .count();
    }

    public ChatUser getByOpenId(String openId) {
        LambdaQueryWrapper<ChatUser> wrapper = new QueryWrapper<ChatUser>().lambda().eq(ChatUser::getWxOpenId, openId);
        return getOne(wrapper);
    }

    public CursorPageBaseResp<ChatUser> getCursorPage(List<Long> memberUidList, MPBaseCursorPageReq req, ChatActiveStatusEnum online) {
        return cursorUtils.getCursorPageByMysql(this, req, wrapper -> {
            wrapper.eq(ChatUser::getOnlineStatus, online.getStatus());//筛选上线或者离线的
            wrapper.in(CollectionUtils.isNotEmpty(memberUidList), ChatUser::getId, memberUidList);//普通群对uid列表做限制
        }, ChatUser::getLastOptTime);
    }

    public void online(Long userId) {
        userMapper.updateOptTimeAndStatus(userId, new Date(), ChatActiveStatusEnum.ONLINE.getStatus());
    }

    public void offline(Long userId) {
        userMapper.updateOptTimeAndStatus(userId,null, ChatActiveStatusEnum.OFFLINE.getStatus());
    }
}

